package bridge

import (
	"gitee.com/tomatomeatman/golang-repository/bricks2/model/dbinfo"
	"gitee.com/tomatomeatman/golang-repository/bricks2/model/msgentity"
	"gitee.com/tomatomeatman/golang-repository/bricks2/utils/app"
	"gitee.com/tomatomeatman/golang-repository/bricks2/utils/ginutil"
)

/**
 * 拦截器忽略路径接口桥接业务操作结构体
 */
type IgnoreUrlService struct {
	app.ServiceBaseFunc
}

var (
	ignoreURLServerName = "" //桥接到登录服务的服务名,默认GBaseSystemServer
	//ignoreURLServerKey  = "" //桥接到登录服务的服务密钥
)

// 初始化
func init() {
	if app.IsNotCloudSystem() { //禁用桥接
		return
	}

	ignoreURLServerName = app.ReadConfigKey("CloudServer", "BaseServerName", "GBaseSystemServer").(string)
	//ignoreURLServerKey = app.ReadConfigKey("CloudServer", "BaseServerKey", "").(string)
}

/**
 * 根据记录编号取对象
 * @param Id 记录编号
 * @return
 */
func (service IgnoreUrlService) FindById(ctx ginutil.Context, entity dbinfo.Entity, id interface{}) *msgentity.MsgEntity {
	m := map[string]interface{}{"Id": id}

	me := BridgeDao{}.Post(ctx, ignoreURLServerName, "/ignore/url/find/id", m, &msgentity.MsgEntity{})
	if !me.Success {
		return me
	}

	return me.Data.(*msgentity.MsgEntity)
}

/**
 * 验证指定url是否在可忽略的访问路径中(给内部拦截器用,直接返回Boolean)
 * @param url 待检验的url
 * @param mustLogin 是否必须登录
 * @return
 */
func (service IgnoreUrlService) CheckIgnoreUrl(ctx ginutil.Context, url string, mustLogin int, userType string) bool {
	m := map[string]interface{}{
		"url":       url,
		"mustLogin": mustLogin,
		"userType":  userType,
	}

	me := BridgeDao{}.Post(ctx, ignoreURLServerName, "/ignore/url/check", m, &msgentity.MsgEntity{})
	if !me.Success { //Post请求未成功
		return false
	}

	me = me.Data.(*msgentity.MsgEntity)
	if !me.Success { //"在指定项目中都没有找到可以免拦截的约定"
		return false
	}

	return me.Data.(bool)
}

/**
 * 清理缓存
 * @return
 */
func (service IgnoreUrlService) ClearCache(ctx ginutil.Context, cacheName, user string) *msgentity.MsgEntity {
	me := BridgeDao{}.Post(ctx, ignoreURLServerName, "/ignore/url/clear/cache", nil, "")
	if !me.Success {
		return me
	}

	return me
}
